package com.stormrage.edu.ctrl.index;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stormrage.edu.serv.Index.IdxImageServ;
import com.stormrage.edu.serv.Index.IdxTrialServ;
import com.stormrage.edu.serv.edu.EduLecServ;
import com.stormrage.edu.serv.student.StuAcctServ;
import com.stormrage.edu.serv.student.StuNoticeServ;
import com.stormrage.entity.edu.EduLec;
import com.stormrage.entity.index.IdxImage;
import com.stormrage.entity.index.IdxTrial;
import com.stormrage.entity.index.rep.IndexRep;
import com.stormrage.entity.student.StuAcct;
import com.stormrage.entity.student.StuNotice;
import com.stormragetech.core.ctrl.BaseCtrl;

/**
 * @Title: IndexCtrl.java
 * @Package com.stormrage.edu.ctrl.index
 * @Description: 首页 Controller
 * @author www.stormragetech.com
 * @date 2016年4月16日
 * @version V1.0
 */
@Controller
public class IndexCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(IndexCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['html.logo']}")
	private String htmlLogo;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Value("#{constants['path.trial']}")
	private String trialPath;

	@Value("#{constants['path.thumb']}")
	private String thumbPath;

	@Autowired
	private EduLecServ eduLecServ;

	@Autowired
	private IdxImageServ idxImageServ;

	@Autowired
	private IdxTrialServ idxTrialServ;

	@Autowired
	private StuAcctServ stuAcctServ;

	@Autowired
	private StuNoticeServ stuNoticeServ;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(HttpServletRequest request, Model model) throws UnsupportedEncodingException {

		logger.debug("【 Controller 】-【 IndexCtrl 】-【 Index 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			if (currentUser.getPrincipal() != null)
				model.addAttribute("user", stuAcctServ.queryByAcct(currentUser.getPrincipal().toString()));

			// ------------------ Controller 操作 ------------------
			List<StuNotice> notice = stuNoticeServ.queryListForIndex();
			List<IdxImage> image = idxImageServ.queryList();
			List<EduLec> lec = eduLecServ.queryListForIndex();
			List<IdxTrial> trial = idxTrialServ.queryListForIndex();

			IndexRep rep = IndexRep.instance(notice, image, lec, trial);

			// ------------------ Model 赋值 ------------------
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("tpath", rootUrl + thumbPath);
			model.addAttribute("data", rep);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug("【 Controller 】-【 IndexCtrl 】-【 Index 】-【 GET 】-【 COMPLETED 】");
		return "index";
	}

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public String index(StuAcct entity, RedirectAttributes redirect) {

		logger.debug("【 Controller 】-【 IndexCtrl 】-【 Index 】-【 POST 】-【 STARTED 】");

		Subject subject = SecurityUtils.getSubject();
		String msg = null;

		if (!subject.isAuthenticated()) {

			try {

				UsernamePasswordToken token = new UsernamePasswordToken();
				token.setUsername(entity.getAcct());
				token.setPassword(entity.getPass().toCharArray());
				SecurityUtils.getSubject().login(token);

			} catch (UnknownAccountException uae) {
				logger.error("用户名不存在错误");
				msg = "用户名不存在";
			} catch (IncorrectCredentialsException ice) {
				logger.error("密码错误");
				msg = "用户名/密码错误";
			} catch (LockedAccountException lae) {
				logger.error("账号锁定错误");
				msg = "账号锁定";
			} catch (AuthenticationException ae) {
				logger.error("unexpected condition.");
				msg = "其他错误";
			}
		}
		redirect.addFlashAttribute("msg", msg);

		logger.debug("【 Controller 】-【 IndexCtrl 】-【 Index 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/";
	}

	@RequestMapping(value = "/result", method = RequestMethod.GET)
	public String result(Model model) {

		logger.debug(" 【 CONTROLLER 】- 【 INDEX 】- 开始运行 ");

		logger.debug(" Constants的字符串为 " + htmlTitle + " | " + htmlLogo);

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			model.addAttribute("htmltitle", htmlTitle);
			model.addAttribute("htmllogo", htmlLogo);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		return "result";
	}

}
